package boardgamer.common.client;

import boardgamer.common.SynchronizedObject;

public abstract class PeriodicTimer {

  private final int period;
  protected SynchronizedObject<Integer> millis;

  protected PeriodicTimer(int period) {
    this.period = period;
    this.millis = new SynchronizedObject<Integer>(period);
  }

  /**
   * update calls onPeriodic er.. periodically based approximately on:
   * period mod time == 0.
   *
   * @param time
   */
  public void update(int time) {
    synchronized (millis) {
      millis.set(millis.get() - time);
      while (millis.get() <= 0) {
        onPeriodic();
        millis.set(millis.get() + period);
      }
    }
  }

  protected abstract void onPeriodic();
}
